#!/bin/bash

# Sealos 部署脚本

echo "🚀 开始部署到 Sealos..."

# 检查必要的工具
check_requirements() {
    echo "📋 检查部署要求..."
    
    if ! command -v docker &> /dev/null; then
        echo "❌ Docker 未安装，请先安装 Docker"
        exit 1
    fi
    
    if ! command -v kubectl &> /dev/null; then
        echo "❌ kubectl 未安装，请先安装 kubectl"
        exit 1
    fi
    
    echo "✅ 所有要求已满足"
}

# 构建 Docker 镜像
build_image() {
    echo "🔨 构建 Docker 镜像..."
    
    if docker build -t car-paint-demo:latest .; then
        echo "✅ Docker 镜像构建成功"
    else
        echo "❌ Docker 镜像构建失败"
        exit 1
    fi
}

# 部署到 Kubernetes
deploy_to_k8s() {
    echo "🚀 部署到 Kubernetes..."
    
    # 创建命名空间（如果不存在）
    kubectl create namespace car-paint-demo --dry-run=client -o yaml | kubectl apply -f -
    
    # 部署应用
    if kubectl apply -f k8s/deployment.yaml; then
        echo "✅ Kubernetes 部署成功"
    else
        echo "❌ Kubernetes 部署失败"
        exit 1
    fi
}

# 等待应用就绪
wait_for_ready() {
    echo "⏳ 等待应用就绪..."
    
    kubectl wait --for=condition=ready pod -l app=car-paint-demo --timeout=300s
    
    if [ $? -eq 0 ]; then
        echo "✅ 应用已就绪"
    else
        echo "❌ 应用启动超时"
        exit 1
    fi
}

# 显示部署信息
show_info() {
    echo "📊 部署信息："
    echo ""
    
    # 显示 Pod 状态
    echo "Pod 状态："
    kubectl get pods -l app=car-paint-demo
    
    echo ""
    
    # 显示 Service 信息
    echo "Service 信息："
    kubectl get services -l app=car-paint-demo
    
    echo ""
    
    # 显示 Ingress 信息
    echo "Ingress 信息："
    kubectl get ingress -l app=car-paint-demo
    
    echo ""
    echo "🌐 访问方式："
    echo "1. 通过 Sealos 控制台访问"
    echo "2. 端口转发: kubectl port-forward service/car-paint-demo-service 8080:80"
    echo "3. 然后访问: http://localhost:8080"
}

# 主函数
main() {
    check_requirements
    build_image
    deploy_to_k8s
    wait_for_ready
    show_info
    
    echo "🎉 部署完成！"
}

# 运行主函数
main
